package utils

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"os"
	"strings"
)

func GetSignedURL(filename string) string  {

	bucket := GetBucket(GetOssClient())

	//获取后缀
	ext := filename[strings.LastIndex(filename, "."):]
	fmt.Println(getcontentType(ext))
	options := []oss.Option{
		oss.ContentType(getcontentType(ext)),
		//oss.ContentType("multipart/form-data"),
	}
	// 签名直传,这里key应该是用户的id
	signedURL, err := bucket.SignURL(filename, oss.HTTPPut, 3600,options...)
	if err != nil {
		fmt.Println(err)
	}
	return signedURL
}

func GetBucket(client *oss.Client) *oss.Bucket  {
	// 获取存储空间。
	bucket, err := client.Bucket("test2020718")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	return bucket
}

func GetOssClient() *oss.Client {
	endpoint:="oss-cn-beijing.aliyuncs.com"
	accessKeyId:="LTAI4GEUnmNYCHpYUZadjXHD"
	accessKeySecret:="msVwXZOtDnr5zA62SRkUUQ3p4kLCwG"
	client, err := oss.New(endpoint, accessKeyId, accessKeySecret)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.Println(client)
	return client
}

func getcontentType(fileExtension string) string {
	//忽略大小写
	if strings.EqualFold(fileExtension,".bmp"){
		return "image/bmp"
	}
	if strings.EqualFold(fileExtension,".jpg"){
		return "image/jpg"
	}
	if strings.EqualFold(fileExtension,".png"){
		return "image/png"
	}
	if strings.EqualFold(fileExtension,".ico"){
		return "image/ico"
	}
	return "nomatch"
}
